# -*- coding: UTF-8 -*-

from .BaseService import BaseService

class WechatUserSyncAuthService(BaseService):
    '''
    ... 如果请求成功，data中的返回数据格式如下
    ... {
    ...     "BaseResponse": {
    ...         "Ret": 0,
    ...         "ErrMsg": ""
    ...     },
    ...     "Count": 2,
    ...     "ContactList": [
    ...         {
    ...             "Uin": 0,
    ...             "UserName": "weixin",
    ...             "NickName": "微信团队",
    ...             "HeadImgUrl": "/cgi-bin/mmwebwx-bin/webwxgeticon?seq=620300063&username=weixin&skey=@crypt_41fe9bb_c0eac9e8285208266499fbad727bda3f",
    ...             "ContactFlag": 1,
    ...             "MemberCount": 0,
    ...             "MemberList": [],
    ...             "RemarkName": "",
    ...             "HideInputBarFlag": 0,
    ...             "Sex": 0,
    ...             "Signature": "微信团队官方帐号",
    ...             "VerifyFlag": 56,
    ...             "OwnerUin": 0,
    ...             "PYInitial": "WXTD",
    ...             "PYQuanPin": "weixintuandui",
    ...             "RemarkPYInitial": "",
    ...             "RemarkPYQuanPin": "",
    ...             "StarFriend": 0,
    ...             "AppAccountFlag": 0,
    ...             "Statues": 0,
    ...             "AttrStatus": 4,
    ...             "Province": "",
    ...             "City": "",
    ...             "Alias": "",
    ...             "SnsFlag": 0,
    ...             "UniFriend": 0,
    ...             "DisplayName": "",
    ...             "ChatRoomId": 0,
    ...             "KeyWord": "wei",
    ...             "EncryChatRoomId": "",
    ...             "IsOwner": 0
    ...         },
    ...         {
    ...             "Uin": 0,
    ...             "UserName": "@@fa6794f287c0ebaeb6d1e883b30bf5e84643cd9affceedccaad139dc897181aa",
    ...             "NickName": "测试",
    ...             "HeadImgUrl": "/cgi-bin/mmwebwx-bin/webwxgetheadimg?seq=0&username=@@fa6794f287c0ebaeb6d1e883b30bf5e84643cd9affceedccaad139dc897181aa&skey=@crypt_41fe9bb_c0eac9e8285208266499fbad727bdabb",
    ...             "ContactFlag": 0,
    ...             "MemberCount": 2,
    ...             "MemberList": [
    ...                 {
    ...                     "Uin": 0,
    ...                     "UserName": "@a6b26f0c46d4e787986c3b5715bb5622",
    ...                     "NickName": "",
    ...                     "AttrStatus": 0,
    ...                     "PYInitial": "",
    ...                     "PYQuanPin": "",
    ...                     "RemarkPYInitial": "",
    ...                     "RemarkPYQuanPin": "",
    ...                     "MemberStatus": 0,
    ...                     "DisplayName": "",
    ...                     "KeyWord": "ase"
    ...                 },
    ...                 {
    ...                     "Uin": 0,
    ...                     "UserName": "@f21acdf3ce1ca6e9cdad364dff6457f949d8e4f4fabe0a99a917b0b27fe9a633",
    ...                     "NickName": "",
    ...                     "AttrStatus": 0,
    ...                     "PYInitial": "",
    ...                     "PYQuanPin": "",
    ...                     "RemarkPYInitial": "",
    ...                     "RemarkPYQuanPin": "",
    ...                     "MemberStatus": 0,
    ...                     "DisplayName": "",
    ...                     "KeyWord": ""
    ...                 }
    ...             ],
    ...             "RemarkName": "",
    ...             "HideInputBarFlag": 0,
    ...             "Sex": 0,
    ...             "Signature": "",
    ...             "VerifyFlag": 0,
    ...             "OwnerUin": 0,
    ...             "PYInitial": "",
    ...             "PYQuanPin": "",
    ...             "RemarkPYInitial": "",
    ...             "RemarkPYQuanPin": "",
    ...             "StarFriend": 0,
    ...             "AppAccountFlag": 0,
    ...             "Statues": 0,
    ...             "AttrStatus": 0,
    ...             "Province": "",
    ...             "City": "",
    ...             "Alias": "",
    ...             "SnsFlag": 0,
    ...             "UniFriend": 0,
    ...             "DisplayName": "",
    ...             "ChatRoomId": 0,
    ...             "KeyWord": "",
    ...             "EncryChatRoomId": "",
    ...             "IsOwner": 0
    ...         }
    ...     ],
    ...     "SyncKey": {
    ...         "Count": 4,
    ...         "List": [
    ...             {
    ...                 "Key": 1,
    ...                 "Val": 685753629
    ...             },
    ...             {
    ...                 "Key": 2,
    ...                 "Val": 685755226
    ...             },
    ...             {
    ...                 "Key": 3,
    ...                 "Val": 685755187
    ...             },
    ...             {
    ...                 "Key": 1000,
    ...                 "Val": 1522386122
    ...             }
    ...         ]
    ...     },
    ...     "User": {
    ...         "Uin": 245700000,
    ...         "UserName": "@f5240561ee7bc2dff04c0fc6863de97956d556015d7f0f16d90baf47957ff222",
    ...         "NickName": "测试001",
    ...         "HeadImgUrl": "/cgi-bin/mmwebwx-bin/webwxgeticon?seq=2011825975&username=@f5240561ee7bc2dff04c0fc6863de97956d556015d7f0f16d90baf47957ff222&skey=@crypt_41fe9bb_c0eac9e8285208266499fbad727bd222",
    ...         "RemarkName": "",
    ...         "PYInitial": "",
    ...         "PYQuanPin": "",
    ...         "RemarkPYInitial": "",
    ...         "RemarkPYQuanPin": "",
    ...         "HideInputBarFlag": 0,
    ...         "StarFriend": 0,
    ...         "Sex": 1,
    ...         "Signature": "<span class=\"emoji emoji1f30a\"></span>嵐が来るぞ",
    ...         "AppAccountFlag": 0,
    ...         "VerifyFlag": 0,
    ...         "ContactFlag": 0,
    ...         "WebWxPluginSwitch": 0,
    ...         "HeadImgFlag": 1,
    ...         "SnsFlag": 17
    ...     },
    ...     "ChatSet": "weixin,@@fa6794f287c0ebaeb6d1e883b30bf5e84643cd9affceedccaad139dc897181aa",
    ...     "SKey": "@crypt_41fe9bb_c0eac9e8285208266499fbad727bd222",
    ...     "ClientVersion": 369493280,
    ...     "SystemTime": 1522391787,
    ...     "GrayScale": 1,
    ...     "InviteStartCount": 2,
    ...     "MPSubscribeMsgCount": 2,
    ...     "MPSubscribeMsgList": [
    ...         {
    ...             "UserName": "@79bf4d74382a27fa8abdbf93fb034501",
    ...             "MPArticleCount": 1,
    ...             "MPArticleList": [
    ...                 {
    ...                     "Title": "ceshi",
    ...                     "Digest": "ceshi",
    ...                     "Cover": "http://mmbiz.qpic.cn/mmbiz_jpg/1qRdrtrbict1KP877vxsqiazkdMsia730KbmoKgiaGS3lhyeMMKaxzSSq4NXkhpC9Y8tXkxbfuGJeS7TFKI2jiboLUg/300?wxtype=jpeg&wxfrom=0",
    ...                     "Url": "http://mp.weixin.qq.com/s?__biz=MjM5MzYxMjI0NQ==&mid=2659127513&idx=6&sn=b8d05c2f69d3aafb98cb4dd2dba22fff&chksm=bd1fd8638a685175042545ba4f2ae3f03bb6607480236840d7f0fe4a1d6177c870744c1ffcde&scene=0#rd"
    ...                 }
    ...             ],
    ...             "Time": 1522385239,
    ...             "NickName": "ceshi"
    ...         }
    ...     ],
    ...     "ClickReportInterval": 600000
    ... }
    '''
    def fetchUserinfoDetail(self, uin):
        userinfoDetailDO = self.core.loader.instance('do', 'UserinfoDetail').get(uin)
        if userinfoDetailDO is None:
            return self.core.lib.outputobj(False, '用户登录信息获取失败')

        currentTime = self.core.loader.module('time').time()
        url = '%s/webwxinit' % userinfoDetailDO.login_url
        params = {
            'r' : int(-currentTime / 1579),
            'pass_ticket' : userinfoDetailDO.pass_ticket
        }
        request = self.core.loader.lib('request', transport_core = True)
        responseRes = request.sPost(mSession = userinfoDetailDO.session, url = url, params = params, data = {'BaseRequest' : userinfoDetailDO.base_request_params}, headers = self.core.config.JSON_UTF8_HEADER)

        if not responseRes.success:
            return responseRes
        
        decodeContentRes = request.decodeJsonContent(responseRes.data, errors = 'replace')
        if not decodeContentRes.success:
            return self.core.lib.outputobj(False, '微信用户详情获取失败，失败原因：%s' % decodeContentRes.message)

        return self.core.lib.outputobj(True, '成功获取微信用户详情', decodeContentRes.data)


    def handleUserinfoContent(self, uin, userinfoDetail):
        userinfoDetailDO = self.core.loader.instance('do', 'UserinfoDetail').get(uin)
        if userinfoDetailDO is None:
            return self.core.lib.outputobj(False, '用户登录信息获取失败')

        if not userinfoDetail or not isinstance(userinfoDetail, dict):
            return self.core.lib.outputobj(False, '用户详情内容数据为空')

        userinfoDetailDO = self._handleUserBaseinfo(userinfoDetailDO, userinfoDetail.get('User', {}))
        userinfoDetailDO = self._handleSyncInfo(userinfoDetailDO, userinfoDetail.get('SyncKey', {}))

        return self.core.lib.outputobj(True, '用户信息获取成功', userinfoDetailDO)


    def _handleUserBaseinfo(self, userinfoDetailDO, baseinfoDict):
        userinfoDetailDO.username = baseinfoDict.get('UserName', '')
        userinfoDetailDO.nickname = baseinfoDict.get('NickName', '')
        avatar = baseinfoDict.get('HeadImgUrl', '')
        userinfoDetailDO.avatar = ''.join((userinfoDetailDO.login_url, avatar)) if avatar else ''
        return userinfoDetailDO


    def _handleSyncInfo(self, userinfoDetailDO, syncInfoDict):
        userinfoDetailDO.action_sync_key = syncInfoDict
        userinfoDetailDO.status_sync_key = '|'.join(['%s_%s' % (i['Key'], i['Val']) for i in syncInfoDict.get('List', {})])
        return userinfoDetailDO


    '''
    ... 信息同步状态检测
    ... 0：同步状态OK
    ... 1：同步失败
    ... 1101：认证过期，重新扫码登录
    '''
    def checkNotifyStatus(self, uin):
        userinfoDetailDO = self.core.loader.instance('do', 'UserinfoDetail').get(uin)
        if userinfoDetailDO is None:
            return self.core.lib.outputobj(False, '用户登录信息获取失败')

        url = '%s/webwxstatusnotify' % userinfoDetailDO.login_url
        params = {
            'lang' : 'zh_CN',
            'pass_ticket' : userinfoDetailDO.pass_ticket
        }
        postData = {
            'BaseRequest' : userinfoDetailDO.base_request_params,
            'Code' : 3,
            'FromUserName' : userinfoDetailDO.username,
            'ToUserName' : userinfoDetailDO.username,
            'ClientMsgId' : int(self.core.loader.module('time').time() * 1e3)
        }

        request = self.core.loader.lib('request', transport_core = True)
        responseRes = request.sPost(mSession = userinfoDetailDO.session, url = url, params = params, data = postData, headers = self.core.config.JSON_UTF8_HEADER)
        
        if not responseRes.success:
            return responseRes

        try:
            content = responseRes.data.json()
            errcode = -1
            if isinstance(content, dict):
                errcode = int(content.get('BaseResponse', {}).get('Ret', -1))
                if errcode == 0:
                    return self.core.lib.outputobj(True, '手机端信息同步开启')
            return self.core.lib.outputobj(False, '信息同步状态检测失败:%s' % responseRes.data.text, None, errcode)
        except Exception as e:
            return self.core.lib.outputobj(False, u'同步异常[%s]' % str(e))
